import pandas as pd
from general_control import General_Strategy
import Indicators.ATRindicator as ATRUtil

# 吊灯止损改进
class Chandelier_V2(General_Strategy):
    def __init__(self,rcInputFrame,side,enter_point,max_high,min_low,atrbase = 2,win_loss_rate = 1.5):
        General_Strategy.__init__(self, rcInputFrame,side,enter_point)
        self.atrbase = atrbase
        self.win_loss_rate = win_loss_rate
        self.init_profit_point = None
        self.init_loss_point = None
        self.max_price = max_high
        self.min_low = min_low

    def get_profit_point(self):
        profit_point = None
        # 吊灯止损的核心是并不设置止盈，只设置止损，因此返回None
        return profit_point
    def get_loss_point(self):
        loss_point = None
        # 计算传入的df的ATR
        atrframe = ATRUtil.ATR(self.rcInputFrame)
        atr = atrframe.iloc[-1]['ATR']
        if self.init_loss_point == None:
            ## 如果持有空仓，说明进入点为卖出，止损点在进入点之上
            if self.side == 0:
                loss_point = self.enter_point + atr*self.atrbase
                self.init_loss_point = loss_point
            ## 如果持有多仓，说明进入点为买入，止损点在进入点之下
            elif self.side == 1:
                loss_point = self.enter_point - atr*self.atrbase
                self.init_loss_point = loss_point
        # 吊灯动态更新
        else:
            ## 持有空仓，止损线向下更新
            if self.side == 0:
                new_loss_point =self.init_loss_point
                # 当前K线最低点超过之前的最低点了，那么进行下探
                if self.rcInputFrame.iloc[-1]['l'] < self.min_low:
                    # 计算前k线最低点与当前k线最低点的插值，越大波动越快，改值大于0
                    price_range = self.min_low - self.rcInputFrame.iloc[-1]['l']
                    self.min_low = self.rcInputFrame.iloc[-1]['l']
                    # 当前价格与进入价格比已经赚了多少，负值为赚，正值为亏
                    profit = self.rcInputFrame.iloc[-1]['c'] -self.enter_point
                    # # 当止损点低于进入点,直接根据价格变化幅度更新止损线
                    # if self.init_loss_point < self.enter_point:
                    #     new_loss_point -= str_w_max * price_range
                    # # 止损点高于进入点，此时可能会亏损
                    # elif self.init_loss_point > self.enter_point:
                    #     # 如果赚的幅度小于ATR的幅度，
                # 选取当前止损点（close）与之前止损点的最低点
                if new_loss_point <self.init_loss_point:
                    loss_point = new_loss_point
                    self.init_loss_point = loss_point
            ## 多仓止损线向上更新
            elif self.side == 1:
                new_loss_point = self.rcInputFrame.iloc[-1]['h'] - atr * self.atrbase
                if new_loss_point > self.init_loss_point:
                    self.init_loss_point = loss_point
        return loss_point

if __name__ == '__main__':
    data_df = pd.read_csv('../data_info/bit_coin.csv', index_col=0)
    # risk = Chandelier(data_df,1)